# -*- coding: utf-8 -*-
# @Time    : 2016/9/7

from mathsolver.functions.base.base import BaseFunction, new_latex
from mathsolver.functions.base.objects import BaseFunc
from mathsolver.functions.hanshu.helper import check_func


class HanShuDaoShuYunSuan(BaseFunction):
    """
    函数的导数运算
    """
    def solver(self, *args):
        func = check_func(args[0])
        f_name, variable, expression = func.name, func.var, func.expression

        # 推导步骤
        if expression.is_Add:
            # 处理减号的问题（减号被当做加号处理）
            intermediate = "+".join("({})'".format(new_latex(argument)) for argument in expression.args).replace(r"+(-", "-(")
        elif expression.is_Mul:
            first_part = "".join("{}".format(new_latex(argument)) for argument in expression.args[:-1])
            second_part = new_latex(expression.args[-1])
            intermediate = "({0})'{1} + {0}({1})'".format(first_part, second_part)
        else:
            intermediate = None
        # 结果
        result = expression.diff(variable)
        # 第 1234 个步骤
        steps12 = "{0}'({1}) = ({2})'".format(f_name, variable, new_latex(expression))
        # 如果不是复合函数的话，省去第3步
        steps34 = " = {}".format(new_latex(result)) if intermediate is None else " = {0} = {1}".format(intermediate, new_latex(result))
        self.steps.append([steps12, steps34])
        self.output.append(BaseFunc({"var": variable, "name": f_name, "type": "deri", "expression": result}))
        self.label.add("函数的导数运算")
        return self


if __name__ == '__main__':
    pass
